package com.feihong.txgw.ui.activity.order;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.feihong.txgw.R;
import com.feihong.txgw.inter.contract.order.IPlaceOrderContract;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.message.UpdateCartMessage;
import com.feihong.txgw.model.bean.deliveryAdr.DeliveryAdrEntity;
import com.feihong.txgw.model.greendao.ShopCarGoodsModel;
import com.feihong.txgw.shopcar.adapter.CreateOrderGoodsAdapter;
import com.feihong.txgw.tx_precenter.PlaceOrderMainPrecenter;
import com.feihong.txgw.ui.activity.user.MyDeliveryAdrActivity;
import com.feihong.txgw.ui.mvp.BaseMVPCompateActivity;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.utils.PreferenceTools;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * @author wangziheng
 * @name txgw_app
 * @class name：com.feihong.txgw.ui.activity.order
 * @class describe: 购物车 生成、提交订单
 * @time 2017/7/31 19:34
 * @change
 * @chang time
 * @class describe
 */
public class ToCreateOrderActivity extends BaseMVPCompateActivity<IPlaceOrderContract.AbPlaceOrderMainPrecenter> implements IPlaceOrderContract.IPlaceOrderMainView {
    @BindView(R.id.shopcar_createOrder_Goods_recyclerView)
    RecyclerView mOrderGoodsRecyclerView;
    @BindView(R.id.shopcar_createOrder_AllPrice_priceFirst)
    TextView mPriceFirst;
    @BindView(R.id.shopcar_createOrder_AllPrice_priceTail)
    TextView mPriceTail;
    @BindView(R.id.shopcar_submit_order)
    TextView mSubmitOrder;
    private LinearLayoutManager mLinearLayoutManager;
    private CreateOrderGoodsAdapter mAdapter;
    private Intent mIntent;
    private List<ShopCarGoodsModel> mOrderGoodsList;
    private DeliveryAdrEntity mDeliveryAdrEntity;
    /**
     * 是否是从购物车界面跳转而是 默认1是  如果是购物车界面跳转过来的  提交订单成功之后要及时刷新购物车
     */
    private int type = 1;
    private String leaveMsg = "";

    @BindView(R.id.top_back_layout)
    RelativeLayout mTitleLayout;
    @BindView(R.id.txt_pagetitle)
    TextView mTitleName;
    @BindView(R.id.btn_back)
    ImageView mTitleBack;
    @BindView(R.id.createOrder_configure)
    TextView mConfigure;

    @BindView(R.id.activity_status_layout)
    View mStatusView;
    @Override
    public void setTheme() {

    }

    @Override
    public void windowStyle() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(Color.WHITE);
        }else {
        }
    }

    @Override
    public int setLayoutID() {
        return R.layout.shopcar_create_order_layout;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        mStatusView.setVisibility(View.GONE);
        type = getIntent().getIntExtra("type", 1);
        mTitleLayout.setFocusable(true);
        mTitleName.setText("确认订单");
        mLinearLayoutManager = new LinearLayoutManager(this);
        mOrderGoodsRecyclerView.setLayoutManager(mLinearLayoutManager);
        mAdapter = new CreateOrderGoodsAdapter(this);
        mOrderGoodsRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnMsgEditChangeListener(new CreateOrderGoodsAdapter.OnMsgEditChangeListener() {
            @Override
            public void setOnMsgChange(int position, String msg) {
                leaveMsg = msg;
            }
        });

        mTitleBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mDeliveryAdrEntity = new DeliveryAdrEntity();
        PreferenceTools.putString(MyDeliveryAdrActivity.SELECT_ADR_KEY, "");
        if (!TextUtils.isEmpty(PreferenceTools.getString(MyDeliveryAdrActivity.DEFAULT_ADR_KEY, null))) {
            mDeliveryAdrEntity = JSON.parseObject(PreferenceTools.getString(MyDeliveryAdrActivity.DEFAULT_ADR_KEY, null), DeliveryAdrEntity.class);
            PreferenceTools.putString(MyDeliveryAdrActivity.SELECT_ADR_KEY, PreferenceTools.getString(MyDeliveryAdrActivity.DEFAULT_ADR_KEY, null));
        }
        mAdapter.setDeliveryAdr(mDeliveryAdrEntity);
    }


    @Override
    public void bindData() {
        mIntent = getIntent();
        if (mIntent != null) {
            Bundle bundle = mIntent.getExtras();
            if (bundle != null) {
                try {
                    String str = bundle.getString("orderInfo");
                    JSONArray jsonArray = new JSONArray(str);
                    mOrderGoodsList = new ArrayList<>();
                    if (jsonArray.length() > 0) {
                        for (int i = 0; i < jsonArray.length(); i++) {
                            ShopCarGoodsModel dbGoodsCartModel = JSON.parseObject(jsonArray.optJSONObject(i).toString(), ShopCarGoodsModel.class);
                            mOrderGoodsList.add(dbGoodsCartModel);
                        }
                        mAdapter.setGoodsList(mOrderGoodsList);
                        accountAllPrice();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    showSystemToast("解析数据失败！请重试");
                }
            }
        }

        mSubmitOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                if (mDeliveryAdrEntity == null || mDeliveryAdrEntity.getAddress() == null) {
                    showDialog(null, "请填写收货地址");
                } else {
                    mSubmitOrder.setClickable(false);
                    showProgressDialog("正在提交...");
                    List<OrderEntity> orderEntities = new ArrayList<OrderEntity>();
                    for (ShopCarGoodsModel goodsEntity : mOrderGoodsList) {
                        OrderEntity orderEntity = new OrderEntity();
                        orderEntity.setSku_num(String.valueOf(goodsEntity.getGoodsNum()));
                        orderEntity.setSku_id(String.valueOf(goodsEntity.getGoodsID()));
                        orderEntities.add(orderEntity);
                    }
                    String jsonOrder = JSON.toJSONString(orderEntities);
                    mPresenter.submitTerminalOrder(mDeliveryAdrEntity.getAddr_id(), String.valueOf(type), leaveMsg, jsonOrder);
                }
            }
        });

        if (TextUtils.isEmpty(PreferenceTools.getString(MyDeliveryAdrActivity.DEFAULT_ADR_KEY, ""))) {
            mDeliveryAdrEntity = new DeliveryAdrEntity();
            mConfigure.setText("");
        } else {
            mDeliveryAdrEntity = JSON.parseObject(PreferenceTools.getString(MyDeliveryAdrActivity.DEFAULT_ADR_KEY, null), DeliveryAdrEntity.class);
            accountAllPrice();
        }
        mAdapter.setDeliveryAdr(mDeliveryAdrEntity);
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode != MyDeliveryAdrActivity.ADR_ITEMCLICK_REQUEST_CODE) {
            return;
        }
        mPresenter.parseBundle(data);

    }

    @Override
    public void submitTerminalOrderResult(String result) {
        try {
            if (activityIsDestory()) {
                return;
            }
            dismissProgressDialog();
            JSONObject jsonObject = new JSONObject(result);
            if ("200".equals(jsonObject.optString("code"))) {

                final String order_sn = jsonObject.getJSONObject("data").getString("order_sn");
                final String price = jsonObject.getJSONObject("data").getString("price");
                if (1 == type) {
                    //更新购物车
                    UpdateCartMessage updateCartMessage = new UpdateCartMessage();
                    updateCartMessage.setAction(UpdateCartMessage.GOTO_SERVICE_GET_DATA);
                    EventBus.getDefault().post(updateCartMessage);
                }
                showDialog(null, "订单提交成功", new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialogInterface) {

                        Intent intent = new Intent();
                        intent.setClass(getActivity(), PayActivity.class);
                        intent.putExtra(PayActivity.INTENT_PAY_TYPE, PayActivity.PAY_TYPE_PRODUCT);
                        intent.putExtra(PayActivity.INTENT_ORDER_ID, order_sn);
                        intent.putExtra(PayActivity.INTENT_PRICE, price);
                        intent.putExtra(PayActivity.INTENT_TITLE, "购买终端");
                        startActivity(intent);
                        finish();
                    }
                });
            } else {
                showDialog(null, jsonObject.optString("msg"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
            showDialog(null, "提交失败，请重新提交");
        }
    }

    @Override
    public void accountAllPrice() {
        double allPrice = 0;
        String strAllPrice = null;
        DecimalFormat df = new DecimalFormat("######0.00");
        BigDecimal one = new BigDecimal("1");
        for (ShopCarGoodsModel goodsEntity : mOrderGoodsList) {
            BigDecimal a1 = new BigDecimal(Double.toString(goodsEntity.getGoodsPrice()));
            BigDecimal a2 = new BigDecimal(Double.toString(goodsEntity.getGoodsNum()));
            BigDecimal result = a1.multiply(a2);

            allPrice += result.divide(one, 2, BigDecimal.ROUND_HALF_UP).doubleValue();

        }
        if (mDeliveryAdrEntity != null && !TextUtils.isEmpty(mDeliveryAdrEntity.getConfigure())) {
            if ("0.00".equals(mDeliveryAdrEntity.getConfigure()) || "0.0".equals(mDeliveryAdrEntity.getConfigure()) || "0".equals(mDeliveryAdrEntity.getConfigure())) {
                mConfigure.setText("免运费");
                strAllPrice = df.format(allPrice + Float.valueOf(mDeliveryAdrEntity.getConfigure()));
            } else {
                mConfigure.setText("运费：¥" + mDeliveryAdrEntity.getConfigure());
                strAllPrice = df.format(allPrice + Float.valueOf(mDeliveryAdrEntity.getConfigure()));
            }
        } else {
            mConfigure.setText("免运费");
            strAllPrice = df.format(allPrice);
        }
        String[] strings = strAllPrice.split("\\.");
        mPriceFirst.setText("¥ " + strings[0] + ".");
        mPriceTail.setText(strings[1]);
    }

    @Override
    public void parseBundle(DeliveryAdrEntity deliveryAdrEntity) {
        mDeliveryAdrEntity = deliveryAdrEntity;
        mAdapter.setDeliveryAdr(mDeliveryAdrEntity);
        accountAllPrice();
    }

    @Override
    public void loadDataComplated() {
        dismissProgressDialog();
        mSubmitOrder.setClickable(true);
    }

    @Override
    public void loadDataError() {
        if (activityIsDestory()) {
            return;
        }
        dismissProgressDialog();

        showDialog(null, getResources().getString(R.string.connect_service_error));
    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return PlaceOrderMainPrecenter.create();
    }

    class OrderEntity {
        String sku_id;
        String sku_num;
        String goodsSuggest;

        public String getSku_id() {
            return sku_id;
        }

        public void setSku_id(String sku_id) {
            this.sku_id = sku_id;
        }

        public String getSku_num() {
            return sku_num;
        }

        public void setSku_num(String sku_num) {
            this.sku_num = sku_num;
        }

        public String getGoodsSuggest() {
            return goodsSuggest;
        }

        public void setGoodsSuggest(String goodsSuggest) {
            this.goodsSuggest = goodsSuggest;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PreferenceTools.putString(MyDeliveryAdrActivity.SELECT_ADR_KEY, "");
    }
}
